﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.IO;

// References:
// http://msdn.microsoft.com/en-us/library/bb862253.aspx
// http://www.andrewconnell.com/blog/archive/2007/01/10/5704.aspx
// http://www.andrewconnell.com/blog/archive/2008/04/15/More-help-on-creating-custom-timer-jobs-and-a-useful.aspx
// http://msdn.microsoft.com/en-us/library/cc406686.aspx
// http://www.harbar.net/articles/APM.aspx
// http://www.bluedoglimited.com/SharePointThoughts/ViewPost.aspx?ID=271
namespace Hvam.SharePoint.Features.IIS {
    public class IISManagementService : SPService {
        private static readonly string SERVICE_NAME = "IISManagementService";

        public static IISManagementService Local {
            get {
                return SPFarm.Local.Services.GetValue<IISManagementService>(SERVICE_NAME);
            }
        }

        IISStateCollection _states;

        public IISStateCollection States {
            get {
                if (_states == null) {
                    _states = new IISStateCollection(this);
                }
                return _states;
            }
        }

        public IISManagementService() {
        }

        public IISManagementService(SPFarm farm) : base(SERVICE_NAME, farm) { 
        }

        public void UpdateState(SPWebApplication webApplication, SPUrlZone zone, SPIisWebSite.SPIisServerState siteState, ApplicationPoolState poolState) {
            try {
                var state = (from s in States where s.WebApplication == webApplication.Id && s.Zone == (int) zone && s.Server == SPServer.Local.Name select s).Single();

                state.WebSiteState = (int) siteState;
                state.ApplicationPoolState = (int) poolState;
                state.Timestamp = DateTime.Now;
                state.Update();            
            } catch {
                var state = new IISState(Guid.NewGuid(), this) { 
                    Server = SPServer.Local.Name, 
                    WebApplication = webApplication.Id,
                    Zone = (int) zone, 
                    WebSiteState = (int) siteState, 
                    ApplicationPoolState = (int) poolState,
                    Timestamp = DateTime.Now };

                States.Add(state);
            }
        }
    }
}
